package com.mediacloud.app.newsmodule.fragment


import android.graphics.Typeface
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.LinearLayout
import android.widget.TextView
import androidx.annotation.RequiresApi
import androidx.fragment.app.Fragment
import androidx.viewpager.widget.ViewPager
import com.flyco.tablayout.listener.OnTabSelectListener
import com.mediacloud.app.assembly.views.TimeLineRelativeLayout
import com.mediacloud.app.fbnavsk.navPaddingTopMatch
import com.mediacloud.app.model.interfaces.DataInvokeCallBack
import com.mediacloud.app.model.news.ArticleListData
import com.mediacloud.app.model.news.CatalogItem
import com.mediacloud.app.nav2.fragment.HqyNavFragment
import com.mediacloud.app.newsmodule.R
import com.mediacloud.app.newsmodule.adaptor.component.ComponentListItemStyleAdaptor
import com.mediacloud.app.newsmodule.utils.NewsListDataInvoker
import com.mediacloud.app.reslib.enums.ToolBarActionF5OrTop
import com.mediacloud.appcloud.project.gxapp.model.utils.MD5Util
import com.scwang.smartrefresh.layout.api.RefreshFooter
import com.scwang.smartrefresh.layout.api.RefreshLayout
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener
import com.scwang.smartrefresh.layout.listener.SimpleMultiPurposeListener
import com.zimeiti.activity.ArmyNumbListFragment
import com.zimeiti.controler.ZiMeiTiDetailController
import com.zimeiti.interfaces.IGetSubscribeNumberTypeCallback
import com.zimeiti.model.attentionlist.PublicNumberType
import kotlinx.android.synthetic.main.fragment_army_number.*
import kotlinx.android.synthetic.main.fragment_army_number.componentContainer
import kotlinx.android.synthetic.main.fragment_army_number.refreshLayout
import kotlinx.android.synthetic.main.fragment_army_number.scroller
import kotlinx.android.synthetic.main.fragment_army_number.tabLayout
import kotlinx.android.synthetic.main.fragment_army_number.viewpager
import kotlinx.android.synthetic.main.fragment_ws24.*


/**
 * 强军号
 */
class ArmyNumberFragment : HqyNavFragment(), ToolBarActionF5OrTop,OnRefreshLoadMoreListener, DataInvokeCallBack<ArticleListData>, IGetSubscribeNumberTypeCallback {

    val titles: MutableList<String> = ArrayList()
    val fragments: MutableList<Fragment> = ArrayList()
    var adapter: PagerAdapter? = null
    var catalogID: String? = null
    var componentAdapter: ComponentListItemStyleAdaptor? = null
    private var ziMeiTiDetailController: ZiMeiTiDetailController? = null
    protected var catalogItem: CatalogItem? = null
    protected var dataInvoker: NewsListDataInvoker? = null
    override fun getLayoutResID(): Int {
        return R.layout.fragment_army_number
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        navPaddingTopMatch()
        if (fragmentArguments != null) {
            saveInstanceArguments = fragmentArguments
            catalogID = saveInstanceArguments?.getString("id")
            catalogItem = saveInstanceArguments?.getParcelable("catalog")
        } else if (saveInstanceArguments != null) {
            catalogID = saveInstanceArguments!!.getString("id")
            catalogItem = saveInstanceArguments!!.getParcelable("catalog")
        }
        componentAdapter = ComponentListItemStyleAdaptor(requireContext(), catalogItem)

        dataInvoker = NewsListDataInvoker(this)
        refreshLayout.setOnMultiPurposeListener(object : SimpleMultiPurposeListener() {
            override fun onFooterMoving(footer: RefreshFooter, isDragging: Boolean, percent: Float, offset: Int, footerHeight: Int, maxDragHeight: Int) {
                scroller.stickyOffset = offset

            }

        })
        ziMeiTiDetailController = ZiMeiTiDetailController()
        ziMeiTiDetailController!!.getPublicNumberType(null, null, this)


        getData()
    }

    private fun getData() {
        dataInvoker?.getContentListWithAd(catalogID, 1, 1, null)


    }

    var oldVerticalOffset: Int = 0
    override fun initView() {
        loadingView = findViewById(R.id.mLoadingView);
        initStateView();
        retryTips?.setOnClickListener {
           // if (currentState != TYPE_LOADING) {
                showStateView(TYPE_LOADING, false)
                onRefresh(refreshLayout)
           // }
        }
        showStateView(TYPE_LOADING, false)
        refreshLayout.setOnRefreshLoadMoreListener(this)


    }

    override fun onRefresh(refreshLayout: RefreshLayout) {
        TimeLineRelativeLayout.headList.clear()
        getData()
    }

    override fun onLoadMore(refreshLayout: RefreshLayout) {
        if (fragments.size == 0) {
            return
        }
        val index = viewpager.currentItem
        val f = fragments[index]
        if (f is OnLoadMoreListener) {
            f.onLoadMore(refreshLayout)
        }
    }

    var oldMd5 = ""

   // var isFlag = true
    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    override fun success(data: ArticleListData?) {
        if (activity==null||requireActivity().isFinishing||requireActivity().isDestroyed){
            return
        }
        refreshLayout.finishRefresh()

        if (data?.state == true) {
            val componentList = data.componentItems
            val stringBuffer = StringBuffer()
            for (i in componentList.indices) {
                stringBuffer.append(componentList.get(i).getOrginData())
            }
            val md5 = MD5Util.MD5Encode(stringBuffer.toString(), "UTF-8")
            if (false) {
                Log.w("YOAKE", "组件数据没变。不刷新界面")
                return
            } else {
                componentAdapter?.listContentData = componentList
                componentAdapter?.clearEvent()
//                if (isFlag){
//                    for (index in 0 until componentList.size) {
//                        val view =
//                            componentAdapter?.getView(index, null, componentContainer) ?: continue
//                        componentContainer.addView(view)
//                    }
//                    componentContainer.postDelayed({
//                        clearAndToFront(componentContainer2,componentContainer)
//                    },300)
//                }else{
//                    for (index in 0 until componentList.size) {
//                        val view =
//                            componentAdapter?.getView(index, null, componentContainer2) ?: continue
//                        componentContainer2.addView(view)
//                    }
//                    componentContainer.postDelayed({
//                        clearAndToFront(componentContainer,componentContainer2)
//                    },300)
//
//                }
//               isFlag = !isFlag
                componentContainer.reset()
                for (index in 0 until componentList.size) {
                    val view = componentAdapter?.getView(index, null, componentContainer) ?: continue
                    componentContainer.addView(view)
                }
                componentContainer.notifyDataSetChanged()
                closeStateView()
            }
            oldMd5 = md5
        }

    }

    fun clearAndToFront(lodLayout:LinearLayout, newLayout:LinearLayout){
        newLayout.bringToFront()
        lodLayout.removeAllViews()
    }

    override fun fault(data: Any?) {
        if (activity==null||requireActivity().isFinishing||requireActivity().isDestroyed){
            return
        }
        refreshLayout.finishRefresh(false)
    }

    override fun updateNumberType(numberType: PublicNumberType?) {
        buildTab(numberType?.data?.meta)
    }

    override fun updateNumberTypeError() {

    }


    private fun buildTab(list: MutableList<PublicNumberType.Data.SubscribeItem>?) {

        list?.forEach {
            titles.add(it.authorTagName)
            fragments.add(ArmyNumbListFragment.newInstance(it.authorTagId))
        }
        viewpager.offscreenPageLimit = fragments.size

        adapter = PagerAdapter(fragments, titles, childFragmentManager)
        viewpager.adapter = adapter
        tabLayout.setViewPager(viewpager)

        tabLayout.setOnTabSelectListener(object : OnTabSelectListener {
            override fun onTabSelect(position: Int) {
                for (i in 0 until tabLayout.getTabCount()) {
                    val textView: TextView = tabLayout.getTitleView(i)
                    if (position == i) {
                        textView.typeface = Typeface.DEFAULT_BOLD
                    } else {
                        textView.typeface = Typeface.DEFAULT
                    }
                }
            }

            override fun onTabReselect(position: Int) {}
        })


        viewpager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
            override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {
            }

            override fun onPageSelected(position: Int) {
                val f = fragments[position] as ArmyNumbListFragment
                refreshLayout?.setNoMoreData(!f.hasMore)
            }

            override fun onPageScrollStateChanged(state: Int) {
            }
        })
    }

    override fun f5() {
        scroller.scrollY = 0
        refreshLayout.setEnableRefresh(true)
        refreshLayout.autoRefresh(200)
    }

    override fun gun() {
    }

    override fun onDestroyView() {
        componentAdapter?.clearEvent()
        super.onDestroyView()
    }
}